<template>
  <div class="upLoad">
    <el-upload
      class="avatar-uploader upLoadBox"
      style="width: 120px; height: 120px; padding: 10px"
      :http-request="upLoad"
      :show-file-list="false"
      action
    >
      <div v-if="type == 1">
        <img
          v-if="url1"
          :src="url1"
          class="img"
          style="width: 100%; height: 100%; border: none"
        />
      </div>
      <div v-else>
        <SvgaIcon v-if="url1" :url="url1" :index="id"></SvgaIcon>
        <i v-else class="el-icon-plus avatar-uploader-icon img"></i>
      </div>
    </el-upload>
  </div>
</template>

<script>
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";
import SvgaIcon from "@/components/PlaySvga";
export default {
  components: { SvgaIcon },
  props: {
    type: {
      default: "1", //1图片2svga
    },
    url: {
      required: true,
    },
    id: {
      required: true,
    },
  },
  data() {
    return {
      url1: this.url,
    };
  },
  methods: {
    async upLoad(file, obj) {
      //   console.log(obj);
      await ossToken({
        type: 0,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-" + res.data.regionId,
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      try {
        let fileNames =
          "/img/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
        //fileNames上传文件的名称
        //file.file上传文件的内容
        let cli = client(this.dataObj);
        let result = cli.multipartUpload(fileNames, file.file);
        result.then(() => {
          self.url1 = "https://img.psychexy.com" + fileNames;
          self.$message({
            message: "上传成功",
            type: "success",
          });
        });
      } catch (e) {
        self.$message.error("上传失败");
      }
    },
  },
  watch: {
    url1() {
      this.$emit("change", this.url1);
    },
  },
};
</script>

<style lang="less" scoped>
.upLoad {
  padding: 10px;
}
</style>